package org.javaforever.cookieshop.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.javaforever.cookieshop.domain.RoleBean;
import org.javaforever.cookieshop.domain.UserBean;
import org.javaforever.cookieshop.service.RoleService;
import org.javaforever.cookieshop.service.UserService;
import org.javaforever.cookieshop.serviceimpl.UserServiceImpl;
import org.javaforever.cookieshop.shiro.UserRegisteAndLogin;
import org.javaforever.cookieshop.utils.BooleanUtil;
import org.javaforever.cookieshop.utils.PDFUtil;
import org.javaforever.cookieshop.utils.POIExcelUtil;
import org.javaforever.cookieshop.utils.POIPPTUtil;
import org.javaforever.cookieshop.utils.StringUtil;
import org.javaforever.cookieshop.utils.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@RequestMapping(value = "/userController")
@RestController
public class UserController {
	public static UserBean tempUser = new UserBean();
	@Autowired
	protected RoleService roleService;
	@Autowired
	protected UserService service;

	@RequestMapping(value = "/activateAllUsers", method = RequestMethod.POST)
	public Map<String,Object> activateAllUsers(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.activateAllUsers(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/activateUser", method = RequestMethod.POST)
	public Map<String,Object> activateUser(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.activateUser(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/addUploadUserPhoto", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> addUploadUserPhoto(MultipartHttpServletRequest request) throws Exception{
        Map<String, Object> result = new TreeMap<String, Object>();
        Iterator iter = request.getFileNames();
        byte[] imageBytes = null;

        while (iter.hasNext()) {
            MultipartFile file = request.getFile(iter.next().toString());

            if (file != null) {
                imageBytes = file.getBytes();
                if (tempUser == null) tempUser = new UserBean();
                tempUser.setPhoto(imageBytes);
                break;
            }
        }
        if (imageBytes != null) {
            result.put("success", true);
            result.put("data", imageBytes);
        } else {
            result.put("success", false);
            result.put("data", null);
        }
        return result;
	}
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public Map<String,Object> addUser(@RequestBody UserBean user) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        String userName = user.getUserName();
        String password = user.getPassword();
        int userCount = service.countUserByUserName(userName);
        if (userCount==0) {
            String[] saltAndCiphertext = UserRegisteAndLogin.encryptPassword(password);

            user.setSalt(saltAndCiphertext[0]);
            user.setPassword(saltAndCiphertext[1]);
            user.setLoginFailure(0);
            user.setActive(true);

            if (tempUser!=null && tempUser.getPhoto()!=null) {
                user.setPhoto(tempUser.getPhoto());
            }
            tempUser = new  UserBean();
            service.addUser(user);
            user = service.findUserByUserName(user.getUserName());
            RoleBean role = roleService.findRoleByRoleName("user");
            service.assignRolesToUser(user.getId(), ""+role.getId());

            result.put("success",true);
            result.put("data",null);
            return result;
        }else {
            result.put("success",false);
            result.put("data",null);
            return result;
        }
	}
	@RequestMapping(value = "/assignRolesToUser", method = RequestMethod.POST)
	public Map<String,Object> assignRolesToUser(Long userId,String roleIds) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        boolean success = service.assignRolesToUser(userId,roleIds);
        result.put("success",success);
        result.put("rows",null);
        return result;
	}
	@RequestMapping(value = "/changePasswordUser", method = RequestMethod.POST)
	public Map<String,Object> changePasswordUser(String userName,String oldPassword,String password) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        UserBean user = service.findUserByUserName(userName);
        String[] saltAndCiphertext = UserRegisteAndLogin.encryptPassword(password);
        user.setLoginFailure(0);
        user.setSalt(saltAndCiphertext[0]);
        user.setPassword(saltAndCiphertext[1]);
        
        service.changePasswordUser(user);
        result.put("success",true);
        result.put("data",null);
        
        return result;
	}
	@RequestMapping(value = "/checkAccessUser", method = RequestMethod.GET)
	public Map<String,Object> checkAccessUser() throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/cloneAllUsers", method = RequestMethod.POST)
	public Map<String,Object> cloneAllUsers(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.cloneAllUsers(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/cloneUser", method = RequestMethod.POST)
	public Map<String,Object> cloneUser(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.cloneUser(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/deleteAllUsers", method = RequestMethod.POST)
	public Map<String,Object> deleteAllUsers(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.deleteAllUsers(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
	public Map<String,Object> deleteUser(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.deleteUser(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/exportPPTUsers")
	public void exportPPTUsers(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.pptx");
            List<UserBean> list = service.listAllUsers();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            POIPPTUtil.exportPPTWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/exportUsers")
	public void exportUsers(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.xls");
            List<UserBean> list = service.listAllUsers();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            POIExcelUtil.exportExcelWorkbookWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/exportUsersPDF")
	public void exportUsersPDF(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.pdf");
            List<UserBean> list = service.listAllUsers();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            PDFUtil.exportPDFWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/exportUsersWord")
	public void exportUsersWord(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception{
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.doc");
            List<UserBean> list = service.listAllUsers();
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            WordUtil.exportWordWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterPPTUsers", method = RequestMethod.GET)
	public void filterPPTUsers(HttpSession session,
		HttpServletResponse response,
		HttpServletRequest request,
		@RequestParam(value = "userName", required = false) String userName,
		@RequestParam(value = "active", required = false) String active,
		@RequestParam(value = "firstName", required = false) String firstName,
		@RequestParam(value = "lastName", required = false) String lastName,
		@RequestParam(value = "email", required = false) String email,
		@RequestParam(value = "isadmin", required = false) String isadmin,
		@RequestParam(value = "gender", required = false) String gender,
		@RequestParam(value = "address", required = false) String address,
		@RequestParam(value = "phone", required = false) String phone,
		@RequestParam(value = "description", required = false) String description) throws Exception{
        UserBean user0 = new UserBean();
        if (!StringUtil.isBlank(userName)) user0.setUserName(userName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) user0.setActive(activeBool);
        if (!StringUtil.isBlank(firstName)) user0.setFirstName(firstName);
        if (!StringUtil.isBlank(lastName)) user0.setLastName(lastName);
        if (!StringUtil.isBlank(email)) user0.setEmail(email);
        Boolean isadminBool = BooleanUtil.parseBoolean(isadmin);
        if (isadminBool != null) user0.setIsadmin(isadminBool);
        if (!StringUtil.isBlank(gender)) user0.setGender(gender);
        if (!StringUtil.isBlank(address)) user0.setAddress(address);
        if (!StringUtil.isBlank(phone)) user0.setPhone(phone);
        if (!StringUtil.isBlank(description)) user0.setDescription(description);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.pptx");
            List<UserBean> list = service.searchUsersByFields(user0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            POIPPTUtil.exportPPTWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterUsersExcel", method = RequestMethod.GET)
	public void filterUsersExcel(HttpSession session,
		HttpServletResponse response,
		HttpServletRequest request,
		@RequestParam(value = "userName", required = false) String userName,
		@RequestParam(value = "active", required = false) String active,
		@RequestParam(value = "firstName", required = false) String firstName,
		@RequestParam(value = "lastName", required = false) String lastName,
		@RequestParam(value = "email", required = false) String email,
		@RequestParam(value = "isadmin", required = false) String isadmin,
		@RequestParam(value = "gender", required = false) String gender,
		@RequestParam(value = "address", required = false) String address,
		@RequestParam(value = "phone", required = false) String phone,
		@RequestParam(value = "description", required = false) String description) throws Exception{
        UserBean user0 = new UserBean();
        if (!StringUtil.isBlank(userName)) user0.setUserName(userName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) user0.setActive(activeBool);
        if (!StringUtil.isBlank(firstName)) user0.setFirstName(firstName);
        if (!StringUtil.isBlank(lastName)) user0.setLastName(lastName);
        if (!StringUtil.isBlank(email)) user0.setEmail(email);
        Boolean isadminBool = BooleanUtil.parseBoolean(isadmin);
        if (isadminBool != null) user0.setIsadmin(isadminBool);
        if (!StringUtil.isBlank(gender)) user0.setGender(gender);
        if (!StringUtil.isBlank(address)) user0.setAddress(address);
        if (!StringUtil.isBlank(phone)) user0.setPhone(phone);
        if (!StringUtil.isBlank(description)) user0.setDescription(description);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.xls");
            List<UserBean> list = service.searchUsersByFields(user0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            POIExcelUtil.exportExcelWorkbookWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterUsersPDF", method = RequestMethod.GET)
	public void filterUsersPDF(HttpSession session,
		HttpServletResponse response,
		HttpServletRequest request,
		@RequestParam(value = "userName", required = false) String userName,
		@RequestParam(value = "active", required = false) String active,
		@RequestParam(value = "firstName", required = false) String firstName,
		@RequestParam(value = "lastName", required = false) String lastName,
		@RequestParam(value = "email", required = false) String email,
		@RequestParam(value = "isadmin", required = false) String isadmin,
		@RequestParam(value = "gender", required = false) String gender,
		@RequestParam(value = "address", required = false) String address,
		@RequestParam(value = "phone", required = false) String phone,
		@RequestParam(value = "description", required = false) String description) throws Exception{
        UserBean user0 = new UserBean();
        if (!StringUtil.isBlank(userName)) user0.setUserName(userName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) user0.setActive(activeBool);
        if (!StringUtil.isBlank(firstName)) user0.setFirstName(firstName);
        if (!StringUtil.isBlank(lastName)) user0.setLastName(lastName);
        if (!StringUtil.isBlank(email)) user0.setEmail(email);
        Boolean isadminBool = BooleanUtil.parseBoolean(isadmin);
        if (isadminBool != null) user0.setIsadmin(isadminBool);
        if (!StringUtil.isBlank(gender)) user0.setGender(gender);
        if (!StringUtil.isBlank(address)) user0.setAddress(address);
        if (!StringUtil.isBlank(phone)) user0.setPhone(phone);
        if (!StringUtil.isBlank(description)) user0.setDescription(description);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.pdf");
            List<UserBean> list = service.searchUsersByFields(user0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            PDFUtil.exportPDFWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/filterUsersWord", method = RequestMethod.GET)
	public void filterUsersWord(HttpSession session,
		HttpServletResponse response,
		HttpServletRequest request,
		@RequestParam(value = "userName", required = false) String userName,
		@RequestParam(value = "active", required = false) String active,
		@RequestParam(value = "firstName", required = false) String firstName,
		@RequestParam(value = "lastName", required = false) String lastName,
		@RequestParam(value = "email", required = false) String email,
		@RequestParam(value = "isadmin", required = false) String isadmin,
		@RequestParam(value = "gender", required = false) String gender,
		@RequestParam(value = "address", required = false) String address,
		@RequestParam(value = "phone", required = false) String phone,
		@RequestParam(value = "description", required = false) String description) throws Exception{
        UserBean user0 = new UserBean();
        if (!StringUtil.isBlank(userName)) user0.setUserName(userName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) user0.setActive(activeBool);
        if (!StringUtil.isBlank(firstName)) user0.setFirstName(firstName);
        if (!StringUtil.isBlank(lastName)) user0.setLastName(lastName);
        if (!StringUtil.isBlank(email)) user0.setEmail(email);
        Boolean isadminBool = BooleanUtil.parseBoolean(isadmin);
        if (isadminBool != null) user0.setIsadmin(isadminBool);
        if (!StringUtil.isBlank(gender)) user0.setGender(gender);
        if (!StringUtil.isBlank(address)) user0.setAddress(address);
        if (!StringUtil.isBlank(phone)) user0.setPhone(phone);
        if (!StringUtil.isBlank(description)) user0.setDescription(description);
        try(OutputStream out = response.getOutputStream()){
            response.addHeader("Content-Disposition", "attachment;filename=Users.doc");
            List<UserBean> list = service.searchUsersByFields(user0);
            List<List<Object>> contents = new ArrayList<>();
            String sheetName = "用户信息表";
            String [] headers = {"序号","用户名","活跃","名字","姓","电子邮件","是否管理员","性别","地址","电话","描述","照片"};
            Boolean [] isImages = {false,false,false,false,false,false,false,false,false,false,false,true};
            
            for (UserBean user:list) {
                Object [] row = {StringUtil.toNullString(user.getId()),user.getUserName(),StringUtil.toNullString(user.getActive()),user.getFirstName(),user.getLastName(),user.getEmail(),StringUtil.toNullString(user.getIsadmin()),user.getGender(),user.getAddress(),user.getPhone(),user.getDescription(),user.getPhoto()};
                contents.add(Arrays.asList(row));
            }
            
            WordUtil.exportWordWithImage(out, sheetName, Arrays.asList(headers), contents, Arrays.asList(isImages));
        }
	}
	@RequestMapping(value = "/findUserById", method = RequestMethod.POST)
	public Map<String,Object> findUserById(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        UserBean user = service.findUserById(id);
        result.put("success",true);
        result.put("data",user);
        return result;
	}
	@RequestMapping(value = "/findUserByUserName", method = RequestMethod.POST)
	public Map<String,Object> findUserByUserName(@RequestParam(value = "userName", required = true) String userName) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        UserBean user = service.findUserByUserName(userName);
        result.put("success",true);
        result.put("data",user);
        return result;
	}
	@RequestMapping(value = "/listActiveUserRolesUsingUserId", method = RequestMethod.POST)
	public Map<String,Object> listActiveUserRolesUsingUserId(@RequestParam (required = false) Long userId) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        Set<RoleBean> set = new TreeSet<RoleBean>();
        if (userId!=null) set = service.listActiveUserRolesUsingUserId(userId);
        result.put("success",true);
        result.put("rows",set);
        return result;
	}
	@RequestMapping(value = "/listActiveUsers", method = RequestMethod.POST)
	public Map<String,Object> listActiveUsers() throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        List<UserBean> list = service.listActiveUsers();
        result.put("success",true);
        result.put("rows",list);
        return result;
	}
	@RequestMapping(value = "/listAllUsers", method = RequestMethod.POST)
	public Map<String,Object> listAllUsers() throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        List<UserBean> list = service.listAllUsers();
        result.put("success",true);
        result.put("rows",list);
        return result;
	}
	@RequestMapping(value = "/listAvailableActiveUserRolesUsingUserId", method = RequestMethod.POST)
	public Map<String,Object> listAvailableActiveUserRolesUsingUserId(@RequestParam (required = false) Long userId) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        Set<RoleBean> set = new TreeSet<RoleBean>();
        if (userId!=null) set = service.listAvailableActiveUserRolesUsingUserId(userId);
        result.put("success",true);
        result.put("rows",set);
        return result;
	}
	@RequestMapping(value = "/loginUser", method = RequestMethod.POST)
	public Map<String,Object> loginUser(@RequestBody UserBean user) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        String salt = service.getSaltUser(user.getUserName());
        user.setPassword(UserRegisteAndLogin.getInputPasswordCiph(user.getPassword(),salt));
        Subject subject = SecurityUtils.getSubject();
        String loginSuccess = UserRegisteAndLogin.userLogin(user);
        subject.getSession().setAttribute("user", user);
        result.put("success",loginSuccess.equals("index"));
        result.put("token",subject.getSession().getId());
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
	public Map<String,Object> registerUser(@RequestBody UserBean user) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        String userName = user.getUserName();
        String password = user.getPassword();
        int userCount = service.countUserByUserName(userName);
        if (userCount==0) {
            String[] saltAndCiphertext = UserRegisteAndLogin.encryptPassword(password);

            user.setSalt(saltAndCiphertext[0]);
            user.setPassword(saltAndCiphertext[1]);
            user.setLoginFailure(0);

            if (tempUser!=null && tempUser.getPhoto()!=null) {
                user.setPhoto(tempUser.getPhoto());
            }
            tempUser = new  UserBean();
            service.registerUser(user);
            user = service.findUserByUserName(user.getUserName());
            RoleBean role = roleService.findRoleByRoleName("user");
            service.assignRolesToUser(user.getId(), ""+role.getId());

            result.put("success",true);
            result.put("data",null);
            return result;
        }else {
            result.put("success",false);
            result.put("data",null);
            return result;
        }
	}
	@RequestMapping(value = "/revokeRolesFromUser", method = RequestMethod.POST)
	public Map<String,Object> revokeRolesFromUser(Long userId,String roleIds) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        boolean success = service.revokeRolesFromUser(userId,roleIds);
        result.put("success",success);
        result.put("rows",null);
        return result;
	}
	@RequestMapping(value = "/searchUsersByFieldsByPage", method = RequestMethod.POST)
	public Map<String,Object> searchUsersByFieldsByPage(@RequestParam(value = "page", required = false) Integer pagenum,
		@RequestParam(value = "rows", required = false) Integer pagesize,
		@RequestParam(value = "last", required = false) String lastFlag,
		@RequestParam(value = "userName", required = false) String userName,
		@RequestParam(value = "active", required = false) String active,
		@RequestParam(value = "firstName", required = false) String firstName,
		@RequestParam(value = "lastName", required = false) String lastName,
		@RequestParam(value = "email", required = false) String email,
		@RequestParam(value = "isadmin", required = false) String isadmin,
		@RequestParam(value = "gender", required = false) String gender,
		@RequestParam(value = "address", required = false) String address,
		@RequestParam(value = "phone", required = false) String phone,
		@RequestParam(value = "description", required = false) String description) throws Exception{
        UserBean user = new UserBean();
        if (!StringUtil.isBlank(userName)) user.setUserName(userName);
        Boolean activeBool = BooleanUtil.parseBoolean(active);
        if (activeBool != null) user.setActive(activeBool);
        if (!StringUtil.isBlank(firstName)) user.setFirstName(firstName);
        if (!StringUtil.isBlank(lastName)) user.setLastName(lastName);
        if (!StringUtil.isBlank(email)) user.setEmail(email);
        Boolean isadminBool = BooleanUtil.parseBoolean(isadmin);
        if (isadminBool != null) user.setIsadmin(isadminBool);
        if (!StringUtil.isBlank(gender)) user.setGender(gender);
        if (!StringUtil.isBlank(address)) user.setAddress(address);
        if (!StringUtil.isBlank(phone)) user.setPhone(phone);
        if (!StringUtil.isBlank(description)) user.setDescription(description);
        if (pagesize==null || pagesize <= 0) pagesize = 10;
        Integer recordCount = service.countSearchUsersByFieldsRecords(user);
        Integer pageCount = (int)Math.ceil((double)recordCount/pagesize);
        if (pageCount <= 1) pageCount = 1;
        if (pagenum==null || pagenum <= 1) pagenum = 1;
        if (pagenum >= pageCount) pagenum = pageCount;
        Boolean lastFlagBool = BooleanUtil.parseBoolean(lastFlag);
        if (lastFlagBool == null) lastFlagBool = false;
        if (lastFlagBool) pagenum = pageCount;
        Map<String,Object> result = new TreeMap<String,Object>();
        List<UserBean> userList = service.searchUsersByFieldsByPage(user,pagesize,pagenum);
        result.put("success",true);
        result.put("rows",userList);
        result.put("total",recordCount);
        result.put("page",pagenum);
        return result;
	}
	@RequestMapping(value = "/softDeleteAllUsers", method = RequestMethod.POST)
	public Map<String,Object> softDeleteAllUsers(@RequestParam(value = "ids", required = true) String ids) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.softDeleteAllUsers(ids);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/softDeleteUser", method = RequestMethod.POST)
	public Map<String,Object> softDeleteUser(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.softDeleteUser(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/toggleOneUser", method = RequestMethod.POST)
	public Map<String,Object> toggleOneUser(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.toggleOneUser(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/toggleUser", method = RequestMethod.POST)
	public Map<String,Object> toggleUser(@RequestParam Long id) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        service.toggleUser(id);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
	@RequestMapping(value = "/updateUploadUserPhoto", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> updateUploadUserPhoto(MultipartHttpServletRequest request) throws Exception{
        Map<String, Object> result = new TreeMap<String, Object>();
        Iterator iter = request.getFileNames();
        byte[] imageBytes = null;

        while (iter.hasNext()) {
            MultipartFile file = request.getFile(iter.next().toString());

            if (file != null) {
                imageBytes = file.getBytes();
                if (tempUser == null) tempUser = new UserBean();
                tempUser.setPhoto(imageBytes);
                break;
            }
        }
        if (imageBytes != null) {
            result.put("success", true);
            result.put("data", imageBytes);
        } else {
            result.put("success", false);
            result.put("data", null);
        }
        return result;
	}
	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	public Map<String,Object> updateUser(@RequestBody UserBean user) throws Exception{
        Map<String,Object> result = new TreeMap<String,Object>();
        UserBean oriUser = service.findUserById(user.getId());
        if (oriUser.getPhoto()!=null) {
            user.setPhoto(oriUser.getPhoto());
        }
        if (tempUser!=null && tempUser.getPhoto()!=null) {
            user.setPhoto(tempUser.getPhoto());
        }
        tempUser = new  UserBean();
        service.updateUser(user);
        result.put("success",true);
        result.put("data",null);
        return result;
	}
}

